package com.wangwei.authoritySystem.controller;

import com.wangwei.authoritySystem.common.Result;
import com.wangwei.authoritySystem.pojo.Permission;
import com.wangwei.authoritySystem.service.PermissionService;
import com.wangwei.authoritySystem.vo.PermissionQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;
    @GetMapping("/list")
    public Result list(PermissionQueryVo permissionQueryVo){
        List<Permission> permissionList = permissionService.findPermissionList(permissionQueryVo);
        return Result.success(permissionList);
    }

    @GetMapping("/parent/list")
    public Result getParentList(PermissionQueryVo permissionQueryVo){
        List<Permission> permissionList = permissionService.findParentPermissionList();
        return Result.success(permissionList);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Permission permission){
        if(permissionService.save(permission)){
            return Result.success(200,"菜单添加成功",null);
        }
        return Result.fail("菜单添加失败");
    }

    @PutMapping("/update")
    public Result update(@RequestBody Permission permission){
        if(permissionService.updateById(permission)){
            return Result.success(200,"菜单修改成功",null);
        }
        return Result.fail("菜单修改失败");
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id){
        if(permissionService.removeById(id)){
            return Result.success(200,"菜单删除成功",null);
        }
        return Result.fail("菜单删除失败");
    }

    /**
     * 检查是否有子菜单
     * @param id
     * @return
     */
    @GetMapping("/check/{id}")
    public Result check(@PathVariable Long id){
        if(permissionService.hasChildren(id)){
            return Result.exist("该菜单下有子菜单，无法删除",true);
        }
        return Result.exist("可删除",false);
    }
}
